<template>
  <div>
      <div>全选 <input type="checkbox" @change="checkAll" v-model="checkall"><span>{{checkall}}</span></div>
      <div v-for="(item,index) in arr" :key="index">
          <div v-if="item.num > 0">
              <b>{{item.checked}}</b>
               <!-- <input type="checkbox" v-model="item.checked"> -->
              <input type="checkbox" v-model="item.checked" @click="checkitem(item.id)">
               <span>{{item.title}}</span>
             <img :src="item.url" alt="">
             <span>{{item.price}}</span>
             <button @click="delFn(item.id)">--</button>
             <span>{{item.num}}</span>
             <button @click="addFn(item.id)">++</button>
          </div>
      </div>
       <p>总个数：{{totalCount}}</p>
        <p>总和 {{totalPrice}}</p>
  </div>
</template>

<script>
import {mapState,mapMutations} from "vuex"
export default {
    computed:{
        ...mapState(["arr"])
    },
    data() {
        return {
            totalCount:0,//总个数
            totalPrice:0 ,// 总价
            checkall:false // 全选
        }
    },
    methods:{
        ...mapMutations(['addGoods',"delGoods","check","quanxuan"]),
        // 点击加加
        addFn(id){
            this.addGoods(id)
        },
        // 点击渐渐
        delFn(id){
              this.delGoods(id)
        },
        // 点击选中与不选中
        checkitem(id){
            this.check(id)
        },
        // 全选
        checkAll() {
            console.log(this.checkall)
            this.quanxuan(this.checkall)
        }

    },
    watch: {
        // 当arr发生改变的时候，里面的东西就执行
        arr: {
            deep: true, // 监听复杂数据类型的时候需要开启深度监听
            // immediate: true,
            handler(newVal, oldVal) {
               console.log(11111)
                // 求总个数
               this.totalCount =  this.arr.reduce((a,b)=>{
                    if (b.checked) {
                        return a + b.num
                    }
                    return a
                },0)
                // 求的总价
                this.totalPrice = this.arr.reduce((a,b)=>{
                    if (b.checked) {
                        return a + b.num*b.price
                    }
                    return a
                },0)
                // 反选
              this.checkall = this.arr.every((item,index) => {
                    // 我不希望没有加入购物车的影响every，所以我让没加入购物车的默认为true
                    if (item.num == 0 ) {
                        return true
                    }
                    return item.checked

                })
            },
            immediate: true
        },
    },
    mounted(){
        // console.log(this.arr)
    }
}
</script>

<style>

</style>